<template>
  <view class="document">
    <view class="sticky">
      <view class="document-input">
        <image src="../../static/serach.png" />
        <input
          :value="searchText"
          placeholder="输入文件名称"
          confirm-type="search"
          :adjust-position="false"
          auto-blur
          placeholder-style="font-size: 28rpx; font-weight: 500; color: #C6C7CB;"
          @confirm="handleSearch"
          @blur="handleBlur"
          @focus="handleFocus"
        />
        <uni-icons
          v-if="searchText"
          type="close"
          color="#999"
          size="24"
          @click="handleClear"
        />
      </view>
    </view>
    <view class="document-bottom">
      <view
        v-for="item in dataList"
        :key="item.id"
        class="document-box"
        @click="preViewFile(item)"
      >
        <view style="width: 80rpx">
          <uni-icons type="folder-add" size="34" color="#666" />
        </view>
        <view class="item-center">
          <view class="item-label">{{ item.name || "" }}</view>
          <view class="item-value"> {{ formatTime(item.add_time) }} </view>
        </view>
        <view style="width: 60rpx" @click.stop="downloadFile(item)">
          <uni-icons type="download" size="30" color="#409eff" />
        </view>
      </view>
    </view>
    <uni-load-more v-if="!isFocus" :status="loadMore" />
  </view>
</template>
<script>
export default {
  data() {
    return {
      searchText: "", // 搜索内容
      isFocus: false, // 是否聚焦
      page: 1, // 页数
      total: 0, // 总条数
      loadMore: "more", // 加载状态
      dataList: [],
    };
  },
  onLoad() {
    this.getList();
  },
  onReachBottom() {
    if (this.loadMore === "more") {
      this.page++;
      this.getList();
    }
  },
  methods: {
    // 搜索
    handleSearch({ detail }) {
      this.searchText = detail.value;
      this.page = 1;
      this.getList();
    },
    // 获取焦点
    handleFocus() {
      this.isFocus = true;
      this.dataList = [];
    },
    // 失去焦点
    handleBlur() {
      this.isFocus = false;
      this.page = 1;
      this.getList();
    },
    // 清空搜索
    handleClear() {
      this.searchText = "";
      this.page = 1;
      this.getList();
    },
    // 获取数据
    getList() {
      this.loadMore = "loading";
      this.$https
        .get("/information/file", {
          name: this.searchText,
          page: this.page,
        })
        .then((res) => {
          let list = res.data.data || [];
          this.dataList = this.page === 1 ? list : this.dataList.concat(list);
          this.total = res.data.total;
          this.changeLoadStratus();
        })
        .catch(() => {
          this.changeLoadStratus();
        });
    },
    // 改变加载状态
    changeLoadStratus() {
      if (this.dataList.length >= this.total) {
        this.loadMore = "noMore";
      } else {
        this.loadMore = "more";
      }
    },
    // 预览文件
    preViewFile(item) {
      if (["jpg", "jpeg", "png", "gif"].includes(item.suffix)) {
        uni.previewImage({
          current: item.file,
          urls: [item.file],
          showmenu: false,
        });
      } else if (
        ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"].includes(item.suffix)
      ) {
        uni.downloadFile({
          url: item.file,
          success: (res) => {
            if (res.statusCode === 200) {
              uni.openDocument({
                filePath: res.tempFilePath,
                showMenu: false,
                success: (res) => {},
                fail: () => {
                  uni.showToast({
                    title: "打开文件失败",
                    icon: "none",
                  });
                },
              });
            }
          },
          fail: () => {
            uni.showToast({
              title: "打开文件失败",
              icon: "none",
            });
          },
        });
      } else {
        uni.showToast({
          title: `暂不支持预览.${item.suffix || ""}格式文件`,
          icon: "none",
        });
      }
    },
    // 下载文件
    downloadFile(item) {
      // #ifdef MP-WEIXIN
      uni.showToast({
        title: "请前往APP中下载文件",
        icon: "none",
      })
      return
      if (["jpg", "jpeg", "png", "gif"].includes(item.suffix)) {
        uni.downloadFile({
          url: item.file,
          success: (res) => {
            if (res.statusCode === 200) {
              uni.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success: () => {
                  uni.showToast({
                    title: "已保存到相册",
                    icon: "none",
                    duration: 3000,
                  });
                },
              });
            }
          },
        });
      } else if (["mp4"].includes(item.suffix)) {
        uni.downloadFile({
          url: item.file,
          success: (res) => {
            if (res.statusCode === 200) {
              uni.saveVideoToPhotosAlbum({
                filePath: res.tempFilePath,
                success: () => {
                  uni.showToast({
                    title: "已保存到相册",
                    icon: "none",
                    duration: 3000,
                  });
                },
              });
            }
          },
        });
      } else if (
        ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"].includes(item.suffix)
      ) {
        uni.downloadFile({
          url: item.file,
          success: (res) => {
            if (res.statusCode === 200) {
              uni.showToast({
                title: "打开文件后，请点击右上角菜单<保存到手机>下载",
                icon: "none",
                duration: 3000,
                success: () => {
                  setTimeout(() => {
                    uni.openDocument({
                      filePath: res.tempFilePath,
                      showMenu: true,
                    });
                  }, 3000);
                },
              });
            }
          },
          fail: () => {
            uni.showToast({
              title: "打开文件失败",
              icon: "none",
            });
          },
        });
      } else {
        uni.showToast({
          title: `由于小程序限制，暂不支持下载.${item.suffix || ""}格式文件`,
          icon: "none",
          duration: 3000,
        });
      }
      // #endif
      // #ifdef APP-PLUS
      var url = item.file;
      let name = item.name + "." + item.suffix;
      let dtask = plus.downloader.createDownload(
        url,
        {
          filename: "file://storage/emulated/0/Download/" + name,
        },
        (d, status) => {
          if (status == 200) {
            uni.showToast({
              title: "已保存到文件夹：/Download/" + name, //保存路径
              icon: "none",
              duration: 5000,
            });
            // plus.runtime.openFile(d.filename);
          } else {
            plus.downloader.clear(); //清除下载任务
            uni.showToast({
              icon: "none",
              title: "下载失败，请稍后重试",
            });
          }
        }
      );
      dtask.start();
      // #endif
      // #ifdef H5
      uni.showToast({
        icon: "none",
        title: "请前往APP中下载文件",
      });
      // #endif
    },
    // 格式化日期
    formatTime(time) {
      if (!time) return "";
      let date = new Date(time * 1000);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      m = m < 10 ? "0" + m : m;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let i = date.getMinutes();
      i = i < 10 ? "0" + i : i;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + m + "-" + d + " " + h + ":" + i + ":" + s;
    },
  },
};
</script>
<style lang="scss" scoped>
.document {
  min-height: calc(100vh - 86rpx);
  background-color: #fff;
  .sticky {
    position: sticky;
    /* #ifdef MP-WEIXIN || APP-PLUS */
    top: 0;
    /* #endif */
    /* #ifdef H5 */
    top: 86rpx;
    /* #endif */
    z-index: 9;
    padding: 20rpx 32rpx;
    background-color: #fff;
  }
  &-input {
    display: flex;
    align-items: center;
    height: 80rpx;
    background: #f6f6fb;
    border-radius: 44rpx;
    padding: 0 24rpx;
    image {
      width: 36rpx;
      height: 36rpx;
      margin-right: 34rpx;
    }
    input {
      flex: 1;
    }
  }
  &-bottom {
    padding: 0 32rpx;
  }
  &-box {
    display: flex;
    align-items: center;
    box-shadow: 0 0 10rpx #c2c9cc;
    border-radius: 20rpx;
    margin-top: 20rpx;
    padding: 20rpx;
    color: #141414;
    &:active {
      background-color: #f0f0f0;
    }
    .item-center {
      flex: 1;
      padding: 10rpx 0;
      font-size: 28rpx;
      .item-label {
        font-size: 28rpx;
        color: #333;
        word-break: break-all;
      }
      .item-value {
        margin-top: 10rpx;
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}
</style>
